#!/usr/bin/env python3
# -*- coding: utf-8 -*
import requests
from json import loads

class LoginTic(object):

    def __init__(self):
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
        }
        # 创建一个网络请求session实现登录验证
        self.session = requests.Session()

    def getImg(self):
        url = "https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand";
        response = self.session.get(url=url, headers=self.headers)
        im = open('img.jpg', 'wb')
        im.write(response.content)
        im.close()

    def checkVerification(self):
        code = input('''
                ---------------------------------------
                        |         |         |  
                   0    |    1    |    2    |     3  
                        |         |         |  
                ---------------------------------------  
                        |         |         |  
                   4    |    5    |    6    |     7  
                        |         |         |  
                ---------------------------------------  
                根据打开的图片识别验证码后手动输入，输入正确验证码对应的位置，例如：2,5 :''')

        soList = code.split(',')
        yanSol = ['35,35', '105,35', '175,35', '245,35', '35,105', '105,105', '175,105', '245,105']
        yanList = []
        for item in soList:
            print
            item
            yanList.append(yanSol[int(item)])
        yanStr = ','.join(yanList)
        checkUrl = "https://kyfw.12306.cn/passport/captcha/captcha-check"
        data = {
            'login_site': 'E',
            'rand': 'sjrand',
            'answer': yanStr
        }
        cont = self.session.post(url=checkUrl, data=data, headers=self.headers)
        # 返回json格式的字符串，用json模块解析
        dic = loads(cont.content)
        chek = dic['result_code']
        return int(chek)

    def loginTo(self):
        userName = input('输入用户名:')
        pwd = input('输入密码:')
        loginUrl = "https://kyfw.12306.cn/passport/web/login"
        data = {
            'username': userName,
            'password': pwd,
            'appid': 'otn'
        }
        result = self.session.post(url=loginUrl, data=data, headers=self.headers)
        dic = loads(result.content)
        mes = dic['result_message']
        if mes == u'登录成功':
            print('恭喜你，登录成功，可以购票!')

        else:
            print('对不起，登录失败，请检查登录信息!')


if __name__ == '__main__':
    # 0:还没有验证  4：成功  5：验证失败  7：过期
    chek = 0
    login = LoginTic()
    login.getImg()
    while not chek==4:
        if chek==4:
            print('验证通过!')
        elif chek==5:
            print('验证失败，请重新验证!')
            chek = login.checkVerification()
        elif chek==7:
            login.getImg()
            chek = login.checkVerification()
        else:
            chek = login.checkVerification()
    login.loginTo()
